import React, { useEffect, useState } from 'react';
import { View, Image, StyleSheet, Alert, } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import axios from 'axios';
import Icon from '@expo/vector-icons/AntDesign';
import { Button } from 'react-native-elements';
import { router } from 'expo-router';

import useResponsive from '@/rem/rem'
const { w, h, fs } = useResponsive()
const AvatarUploader: React.FC = () => {
    const [image, setImage] = useState('');
    const [realstatus, setRealstatus] = useState(false);
    // 请求相册权限并选择图片
    const pickImage = async () => {
        const permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();
        if (!permissionResult.granted) {
            Alert.alert('Permission to access camera roll is required!');
            return;
        }
        const result = await ImagePicker.launchImageLibraryAsync({
            mediaTypes: ImagePicker.MediaTypeOptions.Images,
            allowsEditing: true,
            aspect: [4, 3],
            quality: 0.3,
        });
        if (!result.canceled && result.assets[0]?.uri) {
            setImage(result.assets[0].uri);
        }
    };
    // 上传图片
    const uploadImage = async () => {
        if (!image) {
            Alert.alert('请先选择一张图片');
            return;
        }
        const formData = new FormData();
        const filename = image.split('/').pop();
        const fileType = filename ? filename.split('.').pop() : 'jpg';
        // 使用 fetch 获取文件
        const response = await fetch(image);
        const blob = await response.blob();
        // 创建一个新的 File 对象
        const file = new File([blob], filename, { type: `image/${fileType}` });
        // 将 File 对象添加到 FormData 中
        formData.append('file', file);
        try {
            const { data: { code, base } } = await axios.post('http://192.168.1.18:3000/uploadimg', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
            });
            if (code == 200) {
                Alert.alert('上传成功');
                console.log('成功韩', 1111111111111111);
                identify(base)
            } else {
                Alert.alert('上传失败，请稍后重试');
            }
        } catch (error) {
            console.error(error);
            Alert.alert('上传过程中发生错误');
        }
    };
    const [name, setname] = useState('')
    const identify = async (base) => {
        let { data: { code, data } } = await axios.post(`http://192.168.1.18:3000/shibie`, { img: base })
        if (code == 200) {
            /*  setname(data.姓名.words)
             console.log(data.姓名.words); */
            setRealstatus(true)
            addReal(data.姓名.words)

        }

    }
  const [cid, setcid] = useState('677f8a026b8f7fa143a658de')
    const addReal = async (a) => {
        let obj = {
            name: a,
            cid: cid
        }
        let { data: { code } } = await axios.post('http://192.168.1.18:3000/addreal', obj)
        if (code == 200) {
           router.push('/setting/set')

        }
    }

    
    return (

        <View >
            {
                image!='' ?
                    <View>

                            <View style={styles.big}>
                                <Image source={{ uri: image }} style={styles.img} />
                                <View style={styles.petCardButtonbox}><Button title="完成" onPress={uploadImage} buttonStyle={styles.petCardButton} /></View>
                            </View>
                    </View> :
                    <View style={styles.iconbox}>
                        <Icon name="camerao" size={50} color="#A7ABAA" onPress={pickImage} style={styles.icon} />
                    </View>
            }

        </View>
    );
};

const styles = StyleSheet.create({
    big: {
        width: w(355),
        margin: w(10),
        height: h(250),


    },
    img: {
        width: '100%',
        height: h(250),
        marginBottom: 10,
    },
    iconbox: {
        width: w(355),
        margin: w(10),
        height: h(250),
        borderWidth: 1,
        borderColor: 'gray',

        justifyContent: 'center', // 垂直居中
        alignItems: 'center', // 水平居中
        backgroundColor: 'transparent',


    },
    icon: {
        width: w(70),


        padding: 10, // 可选：添加内边距以确保文本不会紧贴边缘
    },
    petCardButtonbox: {
        width: w(375),
        height: h(80),

        justifyContent: 'center', // 垂直居中
        alignItems: 'center', // 水平居中
        backgroundColor: 'transparent',
        marginTop: 30,
        marginBottom: 30,
    },
    petCardButton: {
        width: w(200),
        height: h(50),
        backgroundColor: 'rgb(48, 193, 228)',
        textAlign: 'center',
        borderRadius: 30,
        padding: 10, // 可选：添加内边距以确保文本不会紧贴边缘
    },
})

export default AvatarUploader;
